import { Controller, Get, Put, Inject, Body } from '@midwayjs/core';
import { UserService } from '../service/user.service';
import { UpdateUserInfoDto } from '../dto/userDto';
import { Validate } from '@midwayjs/validate';
import { Context } from '@midwayjs/koa';

@Controller('/api/user')
export class UserController {
    @Inject()
    userService: UserService;

    @Inject()
    ctx: Context;

    // 获取当前用户信息
    @Get('/myInfo/me')
    async getMyInfo() {
        try {
            // 从JWT中间件解析的用户信息中获取用户ID
            const userId = this.ctx.user?.userId;
            
            if (!userId) {
                return { code: 401, message: '用户身份验证失败', data: null };
            }

            const result = await this.userService.getUserInfo(userId);
            
            if (result.success) {
                return { code: 200, message: '获取用户信息成功', data: result.data };
            } else {
                return { code: 400, message: result.message, data: null };
            }
        } catch (error) {
            console.error('获取用户信息失败:', error);
            return { code: 500, message: '服务器内部错误', data: null };
        }
    }

    // 更新当前用户信息
    @Put('/myInfo/me')
    @Validate()
    async updateMyInfo(@Body() updateUserInfoDto: UpdateUserInfoDto) {
        try {
            // 从JWT中间件解析的用户信息中获取用户ID
            const userId = this.ctx.user?.userId;
            
            if (!userId) {
                return { code: 401, message: '用户身份验证失败', data: null };
            }

            const result = await this.userService.updateUserInfo(userId, updateUserInfoDto);
            
            if (result.success) {
                return { code: 200, message: '用户信息更新成功', data: result.data };
            } else {
                return { code: 400, message: result.message, data: null };
            }
        } catch (error) {
            console.error('更新用户信息失败:', error);
            return { code: 500, message: '服务器内部错误', data: null };
        }
    }
}